use super::gridmap::{self, *};
use image::{GenericImage, GrayImage};
use image::{DynamicImage, RgbaImage};
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
pub fn build_map_arr(arr: &Vec<Vec<u8>>) -> Option<GridMap> {
    // 通过二维数组构建GridMap
    if arr.len() < 1 || arr[0].len() < 1{return None}
    
    let (width, height) = (arr[0].len(), arr.len());
    let mut gridmap = GridMap::new(width as u32, height as u32,1.0);
    
    for (ridx,row) in arr.iter().enumerate() {
        for (cidx,col) in row.iter().enumerate() {
            gridmap.set_cell_u8(cidx as u32, ridx as u32, *col);
        }
    }
    Some(gridmap)
}

pub fn build_map_pic(file_path: &str) -> Option<GridMap> {
    // 通过图片构建GridMap

    let src_img = image::open(file_path).expect("Failed to open image file");
    let gray = src_img.as_luma8().expect("Failed to convert image to grayscale");
    let (width, height) = gray.dimensions();

    let mut  gridmap = GridMap::new(width, height, 0.05);
 
    for (x, y, pixel) in gray.enumerate_pixels() {
        gridmap.set_cell_u8(x, y, 255 - pixel[0]);
    }
    Some(gridmap)
}

pub fn save_gridmap(gridmap: &GridMap, file_path: &str) {
    let (width, height) = (gridmap.get_width(), gridmap.get_height());
    let mut gray = GrayImage::new(width, height);
    for (x, y, pixel) in gray.enumerate_pixels_mut() {
        *pixel = image::Luma([gridmap.get_cell(x, y).enum_u8()]);
    }

    gray.save(Path::new(file_path)).expect("Failed to save image file");
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_map() -> Option<GridMap> {
        let arr = vec![vec![0,0,0,125,255,0], 
                                    vec![0,0,0,250,255,0], 
                                    vec![0,0,0,125,255,0]];
        build_map_arr(&arr)
    }
    #[test]
    fn test_build_map_arr() {
        let arr1 = vec![];
        let arr2 = vec![vec![]];
        let arr3 = vec![vec![0,0,0,125,255,0], vec![0,0,0,250,255,0], vec![0,0,0,125,255,0]];
        assert_eq!(build_map_arr(&arr1), None);
        assert_eq!(build_map_arr(&arr2), None);
        assert_ne!(build_map_arr(&arr3), None);
    }

    #[test]
    fn test_build_map_img() {
        // assert_eq!(build_map_pic(""),None);
        assert_ne!(build_map_pic("resouces/empty_room.png"), None);
    }
    #[test]
    fn test_create_map() {
        
    }

    #[test]
    fn test_save_gridmap() {
        
        let gridmap = create_map().unwrap();
        save_gridmap(&gridmap, "resouces/test.png");
    }
}